/*
 * 版权所有(C)，上海海鼎信息工程股份有限公司，lizhixing，所有权利保留。
 * <p>
 * 项目名：	multi-thread
 * 文件名：	ConcurrencyTest
 * 模块说明：
 * 修改历史：
 * 2022/8/1 - lizhixing - 创建。
 */
package com.lovely602.thread.context;

/**
 * 线程上下文切换非常耗时
 * <p>
 * 线程从保存再到加载的过程就是一次上下文切换
 *
 * @author lizhixing
 */
public class ConcurrencyTest {

    private static final long count = 10000L;

    public static void main(String[] args) throws InterruptedException {
        // 并行方法
        concurrency();
        // 串行方法
        serial();
    }

    private static void serial() {
        long start = System.currentTimeMillis();
        int a = 0;
        for (long i = 0; i < count; i++) {
            a += 1;
        }
        int b = 0;
        for (long i = 0; i < count; i++) {
            b += 1;
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("serial：" + time + "ms,b=" + b + ",a= " + a);

    }

    private static void concurrency() throws InterruptedException {
        long start = System.currentTimeMillis();
        // 可使用lambda表达式替换
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (long i = 0; i < count; i++) {
                    a += 1;
//                    System.out.println("a = " + a);
                }
            }
        });
        thread.start();
        int b = 0;
        for (long i = 0; i < count; i++) {
            b += 1;
//            System.out.println("b = " + b);
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("concurrency main: " + time + "ms,b=" + b);
        // 等待线程thread执行完成
        thread.join();
        time = System.currentTimeMillis() - start;
        System.out.println("concurrency children: " + time + "ms,b=" + b);
    }


}
